package controllers

import (
	"cronjob/models"
	"strings"
	"time"

	"github.com/astaxie/beego"
)

// 禁用命令管理
type BanController struct {
	BaseController
}

//
func (this *BanController) List() {
	this.Data["pageTitle"] = "禁用命令管理"
	this.display()
}

func (this *BanController) Table() {
	//当前第几页
	page, err := this.GetInt("page")
	if err != nil {
		page = 1
	}

	//每页显示几个
	limit, err := this.GetInt("limit")
	if err != nil {
		limit = 5
	}

	this.pageSize = limit
	filters := make([]interface{}, 0)
	filters = append(filters, "status", 0)

	code := strings.TrimSpace(this.GetString("code"))
	if code != "" {
		filters = append(filters, "code__icontains", code)
	}

	// arr := []int{0, 1, 2, 3} //删除的不显示
	// filters = append(filters, "status__in", arr)

	result, count := models.BanGetList(page, this.pageSize, filters...)

	list := make([]map[string]interface{}, len(result))

	for k, v := range result {
		row := make(map[string]interface{})
		row["id"] = v.Id
		row["code"] = v.Code
		row["create_time"] = beego.Date(time.Unix(v.CreateTime, 0), "Y-m-d H:i:s")
		list[k] = row
	}

	this.ajaxList("", MSG_OK, count, list)
}

//删除
func (this *BanController) AjaxDel() {
	id, _ := this.GetInt("id")

	ban, err := models.BanGetById(id)
	if err != nil {
		this.ajaxMsg("不存在", MSG_ERR)
	}

	ban.UpdateTime = time.Now().Unix()
	ban.Status = 1

	if err := ban.Update(); err != nil {
		this.ajaxMsg("", MSG_ERR)
	}
	this.ajaxMsg("操作成功", MSG_OK)
}

func (this *BanController) Add() {
	this.Data["pageTitle"] = "新增禁用命令"

	// 角色
	filters := make([]interface{}, 0)
	filters = append(filters, "status", 1)
	result, _ := models.RoleGetList(1, 1000, filters...)
	list := make([]map[string]interface{}, len(result))
	for k, v := range result {
		row := make(map[string]interface{})
		row["id"] = v.Id
		row["role_name"] = v.RoleName
		list[k] = row
	}

	this.Data["role"] = list

	this.display()
}

func (this *BanController) Edit() {
	this.Data["pageTitle"] = "编辑禁用命令"

	id, _ := this.GetInt("id", 0)
	ban, _ := models.BanGetById(id)
	row := make(map[string]interface{})
	row["id"] = ban.Id
	row["code"] = ban.Code
	this.Data["ban"] = row
	this.display()
}

func (this *BanController) AjaxSave() {
	id, _ := this.GetInt("id")
	if id == 0 {
		ban := new(models.Ban)
		ban.Code = strings.TrimSpace(this.GetString("code"))
		ban.CreateTime = time.Now().Unix()

		if _, err := models.BanAdd(ban); err != nil {
			this.ajaxMsg(err.Error(), MSG_ERR)
		}
		this.ajaxMsg("", MSG_OK)
	}

	ban, _ := models.BanGetById(id)
	//修改
	ban.Id = id
	ban.UpdateTime = time.Now().Unix()
	ban.Code = strings.TrimSpace(this.GetString("code"))

	if err := ban.Update(); err != nil {
		this.ajaxMsg(err.Error(), MSG_ERR)
	}
	this.ajaxMsg("", MSG_OK)
}
